<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox, ElTag, ElImage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import * as admin from '@/api/index.js'
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

const products = ref([]);

const searchKeyword = ref(""); // 搜索关键词
const currentPage = ref(1); // 当前页
const pageSize = 12; // 每页 3 行 4 列
const total = ref(0);

// **计算总数据量**
const filteredProducts = computed(() =>
  products.value.filter((product) => product.name.includes(searchKeyword.value.trim()))
);


// **分页计算**
const currentProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  return filteredProducts.value.slice(start, start + pageSize);
});

// **搜索产品时，重置到第一页**
const searchProducts = () => {
  findData();
  currentPage.value = 1;
};

// **弹出框相关**
const dialogVisible = ref(false);
const selectedProduct = ref(null);
const purchaseQuantity = ref(1);
const product_id = ref(null);

// **点击产品卡片打开弹窗**
const openDialog = (product) => {
  product_id.value = product.id;
  selectedProduct.value = { ...product };
  purchaseQuantity.value = 1; // 购买数量重置
  dialogVisible.value = true;
};

// **计算总金额**
const totalAmount = computed(() => {
  return selectedProduct.value ? purchaseQuantity.value * selectedProduct.value.price : 0;
});

// **购买逻辑**
const buyProduct = async () => {
  if (!selectedProduct.value) return;

  if (purchaseQuantity.value > selectedProduct.value.stock) {
    ElMessage.error("购买数量超过库存！");
    return;
  }
  const res = await admin.addOrders({
    currentPage: currentPage.value,
    token: tokenStore.token,
    productId: selectedProduct.value.id,
    totalPrice: totalAmount.value,
    quantity: purchaseQuantity.value
  });
  if (res.code == 0) {
    ElMessage.success(`购买成功！购买 ${purchaseQuantity.value} 件 ${selectedProduct.value.name}`);
  }
  findData();
  dialogVisible.value = false;
};

const findData = async () => {
  const res = await admin.findProduct({
    currentPage: currentPage.value,
    token: tokenStore.token,
    name:searchKeyword.value
  });
  if (res.code == 0) {
    products.value = res.data;
    total.value = res.total;
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  findData();
};


findData()

</script>

<template>
  <div class="container">
    <!-- 搜索框 -->
    <div class="search-bar">
      <el-input v-model="searchKeyword" placeholder="请输入产品名称" clearable class="search-input" />
      <el-button type="primary" class="search-btn" @click="searchProducts">🔍 搜索</el-button>
    </div>

    <!-- 产品列表 -->
    <el-row :gutter="20">
      <el-col v-for="product in products" :key="product.id" :span="6">
        <el-card shadow="hover" class="product-card" @click="openDialog(product)">
          <div class="image-container">
            <img :src="product.img" class="product-image" />
          </div>
          <div class="product-info">
            <span class="product-name">{{ product.name }}</span>
            <span class="price">💰 ¥{{ product.price }}</span>
            <span class="stock">库存: {{ product.stock }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 产品详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="产品详情" width="500px">
      <div v-if="selectedProduct">
        <div class="dialog-content">
          <img :src="selectedProduct.img" class="dialog-image" />
          <div class="dialog-info">
            <h3>{{ selectedProduct.name }}</h3>
            <p class="desc">{{ selectedProduct.desc }}</p>
            <p class="price">💰 价格: ¥{{ selectedProduct.price }}</p>
            <p class="stock">库存: {{ selectedProduct.stock }}</p>
            <div class="purchase">
              <el-input-number
                v-model="purchaseQuantity"
                :min="1"
                :max="selectedProduct.stock"
                label="购买数量"
              />
              <span class="total-price">总金额: ¥{{ totalAmount }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="buyProduct">购买</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 页面整体 */
.container {
  padding: 20px;
}

/* 搜索框 */
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  justify-content: center;
}
.search-input {
  width: 300px;
}
.search-btn {
  background: linear-gradient(45deg, #007bff, #0056b3);
  border: none;
  color: white;
}

/* 产品卡片 */
.product-card {
  cursor: pointer;
  border-radius: 10px;
  transition: transform 0.2s ease-in-out;
  padding: 0;
  overflow: hidden;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.product-card:hover {
  transform: scale(1.03);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
 
/* 图片区域 */
.image-container {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f8f8f8;
  border-bottom: 1px solid #eee;
}
.product-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

/* 产品信息 */
.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  font-size: 14px;
}
.product-name {
  flex: 1;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.price {
  color: #ff5722;
  font-weight: bold;
}
.stock {
  color: #666;
}

/* 分页 */
.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 弹出框 */
.dialog-content {
  display: flex;
  gap: 10px;
}
.dialog-image {
  width: 180px;
  height: 180px;
  object-fit: cover;
  border-radius: 5px;
}
.dialog-info {
  flex: 1;
}
.desc {
  color: #666;
}
.purchase {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}
.total-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff5722;
}





.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

::v-deep(.el-pagination) {
  font-size: 18px; 
}

::v-deep(.el-pagination .el-pager li) {
  padding: 0 12px;    
  height: 40px;
  line-height: 40px;
  font-size: 18px;
}

::v-deep(.el-pagination button) {
  font-size: 18px;
  padding: 0 12px;
}
</style>